<?php
class Push_By_Token_Controller  {
	private  $data;
	function __construct($db) {
		$this->data = $db;
	}
	
	function push($content) {
		ini_set('memory_limit','500M');
		set_time_limit(0);
		while (1){
			$count1 = $this->count_status_no_push();
			$length = ceil($count1/20);
			$length = $length > 1 ? $length:1;
			$minID = 0;
			$forCount = ceil($count1/$length);
			for ($i=0;$i<$forCount;$i++) {
				$this->triggerRequest($minID ,$length,$content);
				$minID = $minID + $length;
			}
			sleep(ceil(0.2*$length));
			$count2 = $this->count_status_no_push();
			if (empty($count2) || $count1 == $count2) {
				return "Game Over!Res1=".$count1.",Res2=".$count2;
			}
		}
	}
	
	function triggerRequest($min,$length,$content)
	{
		$method = "GET";  //可以通过POST或者GET传递一些参数给要触发的脚本
		$url = "127.0.0.1";
		$fp = fsockopen($url,80, $errno, $errstr, 30);
		if (!$fp){
			return FALSE;
		}
		$path = __FILE__;
		$getPath = '/'.basename(dirname(ROOTPATH)).'/'.basename(ROOTPATH)."/application/controllers/push/push_app.php?min=$min&length=$length&content=$content";
		$header = "GET ".$getPath."  / HTTP/1.1\r\n";
		$header .= "Host: www.example.com\r\n";
		$header .= "Connection: Close\r\n\r\n";
		//echo $_SERVER['SCRIPT_NAME'].'<br>';
		//echo $header.'<br>';
		$res = fwrite($fp, $header);
		//echo $res.'<br>';
		fclose($fp);
		return true;
	}
	
	function count_status_no_push()
	{
		$sql="select count(token) as remain from tmp_token where status = 1;";
		$this->data->query($sql);
		$result = $this->data->get_array('default');
		if(!$result){
			return -1;
		}
		return $result['remain'];
	}
}

?>